package cn.jsony.org.service.impl;

import cn.jsony.basic.service.impl.BaseServiceImpl;
import cn.jsony.org.domain.Department;
import cn.jsony.org.mapper.DepartmentMapper;
import cn.jsony.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional//默认只读为false，默认传播机制为REQUIRED[有且仅有一个事务]
    @Override
    public void add(Department department) {
        departmentMapper.save(department);

        //如果没有选择上级部门
        if(department.getParent()==null || department.getParent().getId()==null){
            //只添加自己的id - 自增长id
            department.setDirPath("/"+department.getId());
        }else{
            //获取上级部门id
            Long parent_id = department.getParent().getId();
            //获取上级部门的dirPath
            String parent_dirPath = departmentMapper.loadById(parent_id).getDirPath();
            //组装自己的id
            department.setDirPath(parent_dirPath+"/"+department.getId());
        }
        //更新到数据库
        departmentMapper.update(department);
    }
    @Override
    public List<Department> deptTree() {
        //找出所有的部門，把他们装到一个集合中
        List<Department> departments = departmentMapper.loadAll();
        //把所有的数据装到内存中，用map
        Map<Long, Department> map = new HashMap<>();
        for (Department department : departments) {
            //把每个对象的id作为map的key，对象作为value
            map.put(department.getId(),department);
        }

        //前端需要得到的数据，集合树
        List<Department> deptTree = new ArrayList<>();
        //遍历所有的部门的集合
        for (Department department : departments) {
            if(department.getParent_id()==null){
                //如果当前部门的Parent_id为null，就是顶级部门，就把他装到集合树里
                deptTree.add(department);
            }else {
                Long parent_id = department.getParent_id();
                //如果是次级部门，先通过map的Parent_id找到父部门，再把当前部门装到父部门的children集合中
                Department parentDepartment = map.get(parent_id);
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }


}
